//
//  DownloadArticle.m
//  JianChaRiBao
//
//  Created by Changxy on 13-6-6.
//  Copyright (c) 2013年 wzyk. All rights reserved.
//

#import "DownloadArticle.h"
#import "DataBase.h"
@implementation DownloadArticle
static DownloadArticle * downloadArticle;
- (id)init
{
    self = [super init];
    if (self) {
        downloadArray = [[NSMutableArray alloc]init];
    }
    return self;
}
+ (DownloadArticle *)shareDownloadArticle{
    
    if (!downloadArticle) {
        downloadArticle = [[DownloadArticle alloc]init];
    }
    
    return downloadArticle;
}
- (void)downloadWithInfo:(NSDictionary *)infoDict{
    NSLog(@"dict:%@",infoDict);
    [downloadArray addObject:[infoDict objectForKey:@"item_id"]];
    
    NSArray * chapterArray = [infoDict objectForKey:@"chapter_list"];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSInteger successCount = 0;
        NSInteger failCount = 0;
        for (NSDictionary * dict in chapterArray) {
            NSString * nc_id = [dict objectForKey:@"nc_id"];
            id obj = [[DataRequest sharedRequest] getNovelChapterInfo:nc_id];
            if (obj != nil && [obj isKindOfClass:[NSString class]]) {
                successCount ++;

            }else{
                failCount ++;
                id obj =[[DataRequest sharedRequest] getNovelChapterInfo:nc_id];
                if (obj != nil && [obj isKindOfClass:[NSString class]]) {
                    successCount ++;
                    failCount --;
                    
                }else{
                }

            }
            dispatch_async(dispatch_get_main_queue(), ^{
                NSDictionary * postDict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:successCount + failCount],@"count", [NSNumber numberWithInteger:chapterArray.count] ,@"arrayCount",[infoDict objectForKey:@"item_id"],@"itemID", nil];
                [[NSNotificationCenter defaultCenter] postNotificationName:KDownloading object:postDict];
            });

        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [downloadArray removeObject:[infoDict objectForKey:@"item_id"]];
            NSDictionary * completeDict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInteger:successCount],@"SucceseCount",[NSNumber numberWithInteger:failCount],@"failCount",[infoDict objectForKey:@"item_id"],@"itemID", nil];
            [[DataBase shareDB]insertInfo:infoDict];
            [[NSNotificationCenter defaultCenter] postNotificationName:KDownloadComplete object:completeDict];

        });
        

    });
}
-(void)downloadMagaWithArray:(NSArray *)array dict:(NSDictionary *)infoDict{
    NSString * itemidStr = [[array lastObject] objectForKey:@"magitemid"];
    NSString * itemID = [[array lastObject] objectForKey:@"magitemid"];
    [downloadArray addObject:itemID];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSInteger successCount = 0;
        NSInteger failCount = 0;

        for (NSDictionary * dict in array) {
            NSString * idStr = [dict objectForKey:@"itemid"];
            id obj = [[DataRequest sharedRequest] getArticleInfo:idStr];
            if (obj && [obj isKindOfClass:[NSString class]]) {
                successCount ++;
            }else{
                failCount ++;
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                NSDictionary * postDict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:successCount + failCount],@"count", [NSNumber numberWithInteger:array.count] ,@"arrayCount", itemidStr,@"itemID", nil];
                [[NSNotificationCenter defaultCenter] postNotificationName:KDownloading object:postDict];
            });

 
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [downloadArray removeObject:itemID];
            NSDictionary * completeDict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInteger:successCount],@"SucceseCount",[NSNumber numberWithInteger:failCount],@"failCount",itemidStr,@"itemID", nil];
            NSDictionary * postDict = [NSDictionary dictionaryWithObjectsAndKeys:[infoDict objectForKey:@"image"],@"cover_image",[infoDict objectForKey:@"magitemid"],@"item_id",[infoDict objectForKey:@"magazinename"],@"item_name",[[array objectAtIndex:0] objectForKey:@"itemid"],@"nc_id",[infoDict objectForKey:@"catalogid"],@"catalogid",nil];
            
            [[DataBase shareDB] insertMagaInfo:postDict];

            [[NSNotificationCenter defaultCenter] postNotificationName:KDownloadComplete object:completeDict];

        });
    });

}
-(BOOL)isDownloadingWhich:(NSString *)itemID{
    NSLog(@"itemid:%@ downloadArray%@:",itemID,downloadArray);
    return [downloadArray containsObject:itemID];
}

- (void)downloadNewspaperWithArray:(NSArray *)array info:(NSDictionary *)infoDict
{
    NSString *itemID = infoDict[@"item_id"];
    if ([self hasNewspaperDownloaded:itemID]) {
        NSLog(@"已下载");
        return;
    }
    NSLog(@"开始下载");
    [downloadArray addObject:itemID];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        for (NSDictionary *page in array) {
            if (![page[@"is_page"] boolValue]) {
                NSLog(@"开始下载page：%@",page[@"page_id"]);
                [[DataRequest sharedRequest] getNewspaperSingleArticle:page[@"page_id"]];
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [downloadArray removeObject:itemID];
            NSMutableArray *downlaoded = [[[NSUserDefaults standardUserDefaults] objectForKey:@"download_newspaper"] mutableCopy];
            if (downlaoded == nil) {
                downlaoded = [NSMutableArray array];
            }
            [downlaoded addObject:infoDict];
            [[NSUserDefaults standardUserDefaults] setObject:downlaoded forKey:@"download_newspaper"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"didDownloadNewspaper" object:nil];
        });
    });
}

- (BOOL)hasNewspaperDownloaded:(NSString *)itemID
{
    NSArray *array = [[NSUserDefaults standardUserDefaults] objectForKey:@"download_newspaper"];
    for (NSDictionary *dic in array) {
        if ([dic[@"item_id"] isEqualToString:itemID]) {
            return YES;
        }
    }
    
    return NO;
}

- (NSArray *)getDownloadedNewspaper
{
    NSArray *array = [[NSUserDefaults standardUserDefaults] objectForKey:@"download_newspaper"];
    NSLog(@"getDownloadedNewspaper>>>>%@",array);
    return array;
}
@end
